/**
 *
 */
package com.itee.protocal;

import java.nio.ByteBuffer;

/**
 * @author gonglei
 */
public class FnTools {

    public static byte[] convertFnToByte(int fn) {
        fn--;
        byte[] dt = new byte[2];
        byte mod = (byte) (fn % 8);
        dt[0] = 0x01;
        dt[0] = (byte) (dt[0] << mod);
        dt[1] = (byte) (fn / 8);
        return dt;
    }

    public static byte[] convertDaToByte(int p) {
        if (p == 0) {
            return new byte[2];
        } else {
            p--;
            byte[] da = new byte[2];
            byte mod = (byte) (p % 8);
            da[0] = 0x01;
            da[0] = (byte) (da[0] << mod);
            da[1] = (byte) (p / 8 + 1);
            return da;
        }
    }

    public static int convertToFn(byte dt1, byte dt2) {
        int i = 0;
        if (dt1 < 0) {
            i = 8;
        } else {
            while (dt1 != 0) {
                dt1 >>= 1;
                i++;
            }
        }
        int fnValue = dt2 * 8 + i;
        return fnValue;
    }

    public static int convertToDa(byte da1, byte da2) {
        int i = 0;
        if (da1 < 0) {
            i = 8;
        } else {
            byte da1Temp = da1;
            while (da1Temp != 0) {
                da1Temp >>= 1;
                i++;
            }
        }
        return (da2 - 1) * 8 + i;
    }

    public static int getMesurePort(ByteBuffer buffer) {
        byte da1 = buffer.get();
        byte da2 = buffer.get();
        return convertToDa(da1, da2);
    }

    public static int convertToFn(ByteBuffer buffer) {
        byte dt1 = buffer.get();
        byte dt2 = buffer.get();
        return convertToFn(dt1, dt2);
    }

}
